package bjut.zrpc.core.optimization.utils;

import org.apache.curator.shaded.com.google.common.util.concurrent.ThreadFactoryBuilder;
import org.springframework.util.StringUtils;

import java.util.concurrent.*;

/**
 * @Author: zhuzhiming
 * @Date: 2022/6/23 23:41
 */
public class ThreadPoolUtil {

    private static final ConcurrentHashMap<String, ExecutorService> THEAD_POOL_MAP = new ConcurrentHashMap<>();

    public static ThreadFactory buildThreadFactory(String prefix, Boolean daemon) {

        if (StringUtils.hasLength(prefix)) {
            return new ThreadFactoryBuilder().setNameFormat(prefix + "-%d")
                    .setDaemon(daemon != null && daemon)
                    .build();
        }

        return Executors.defaultThreadFactory();

    }

    public static void shutdownAllThreadPool() {
        THEAD_POOL_MAP.entrySet().parallelStream().forEach(threadPool -> {
            ExecutorService executorService = threadPool.getValue();
            executorService.shutdown();

            try {
                executorService.awaitTermination(3000, TimeUnit.MILLISECONDS);
            } catch (InterruptedException e) {
                throw new RuntimeException(e.getMessage());
            }

        });
    }

}
